package com.emuporium.gymrat.server.exercise;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.emuporium.gymrat.server.data.Exercise;
import com.emuporium.gymrat.server.data.ExerciseDB;
import com.emuporium.gymrat.server.data.User;
import com.emuporium.gymrat.server.data.UserDB;

@SuppressWarnings("serial")
public class ExerciseListServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		User user = UserDB.selectUser(request.getRemoteUser());
		request.setAttribute("user", user);
		boolean isAdmin;
		int userId;

		ArrayList<Exercise> exercises = new ArrayList<Exercise>();
		if (user != null) {
			isAdmin = user.isAdmin();
			userId = user.getId();
		} else {
			isAdmin = false;
			userId = 0;
		}


		Cookie[] cookies = request.getCookies();
		String cookieName = "assignment3";
		String cookieValue = "";
		boolean found = false;

		for (int i = 0; i < cookies.length; i++) {
			Cookie cookie = cookies[i];
			if (cookieName.equals(cookie.getName())) {
				cookieValue = "This cookie already exists! You are a returning user";
				found = true;

			}
		}
		if (!found) {
			cookieValue = "This cookie is new! You are visiting for the first time";
		}
		
		Exercise assignment3Exercise = new Exercise();
		assignment3Exercise.setName("This shouldn't be visible");
		HttpSession session = request.getSession();
		session.setAttribute("assignment3", assignment3Exercise);

		Cookie assignment3Cookie = new Cookie("assignment3",
				cookieValue);
		assignment3Cookie.setMaxAge(-1);
		assignment3Cookie.setPath("/");
		response.addCookie(assignment3Cookie);

		exercises = ExerciseDB.searchExercises(userId, 0, isAdmin);
		request.setAttribute("exercises", exercises);

		String url = "/exercise/list.jsp";
		RequestDispatcher dispatcher = getServletContext()
				.getRequestDispatcher(url);
		dispatcher.forward(request, response);
	}

}
